<script setup>
import { ref } from 'vue'
import PageContainer from '@/components/PageContainer.vue'
import { userUpdatePasswordService } from '@/api/user.js'
import { useUserStore } from '@/stores/index.js'
import { useRouter } from 'vue-router'

// 定义表单数据
const pwdForm = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})

// 定义表单引用
const pwdFormRef = ref()

const userStore = useUserStore()
const router = useRouter()

// 自定义校验规则
const validateNewPwd = (rule, value, callback) => {
  if (value === pwdForm.value.old_pwd) {
    callback(new Error('新密码不能与原密码相同'))
  } else {
    callback()
  }
}

const validateRePwd = (rule, value, callback) => {
  if (value === pwdForm.value.new_pwd) {
    callback()
  } else {
    callback(new Error('确认密码与新密码不一致'))
  }
}

// 表单校验规则
const rules = {
  old_pwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度必须在6-15个字符之间', trigger: 'blur' }
  ],
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度必须在6-15个字符之间', trigger: 'blur' },
    { validator: validateNewPwd, trigger: 'blur' }
  ],
  re_pwd: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度必须在6-15个字符之间', trigger: 'blur' },
    { validator: validateRePwd, trigger: 'blur' }
  ]
}

// 提交表单
const submitForm = async () => {
  pwdFormRef.value?.validate()
  await userUpdatePasswordService(pwdForm.value)
  ElMessage.success('修改密码成功')
  // 更新后退出当前登录，重新登录
  userStore.setToken('')
  userStore.setUser({})

  // 拦截路由
  await router.push('/')
}

// 重置表单
const resetForm = () => {
  pwdFormRef.value?.resetFields()
}
</script>

<template>
  <page-container title="重置密码">
    <el-form
      ref="pwdFormRef"
      :model="pwdForm"
      :rules="rules"
      label-width="80px"
      style="width: 400px; margin-top: 20px"
      status-icon
    >
      <el-form-item label="原密码" prop="old_pwd">
        <el-input
          v-model="pwdForm.old_pwd"
          type="password"
          placeholder="请输入原密码"
          show-password
        />
      </el-form-item>

      <el-form-item label="新密码" prop="new_pwd">
        <el-input
          v-model="pwdForm.new_pwd"
          type="password"
          placeholder="请输入新密码"
          show-password
        />
      </el-form-item>

      <el-form-item label="确认密码" prop="re_pwd">
        <el-input
          v-model="pwdForm.re_pwd"
          type="password"
          placeholder="请再次输入新密码"
          show-password
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">修改密码</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </page-container>
</template>
